package com.audaque.springboot.foshanupload.web.mpdemo.mpgt.action;

import cn.hutool.core.lang.UUID;
import com.audaque.springboot.foshanupload.web.mpdemo.mpgt.model.pojo.SysUserMpgtPojo;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zgb
 * @desc ...
 * @date 2023-05-29 08:53:23
 */
@RestController
@RequestMapping("sqlSession")
public class SqlSessionController {




    @Operation(summary = "列表查询")
    @RequestMapping(value = "/run", method = {RequestMethod.GET})
    public      List<SysUserMpgtPojo>  run() throws Exception {
        String sql = "select * from test_example limit 1,10";

        Class<SysUserMpgtPojo> entityClass = SysUserMpgtPojo.class;
        // INFO: DCTANT: 2022/9/29 使用MybatisPlus自己的SqlHelper获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = SqlHelper.sqlSessionFactory(SysUserMpgtPojo.class);
        // INFO: DCTANT: 2022/9/29 通过SqlSessionFactory创建一个新的SqlSession，并获取全局配置
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Configuration configuration = sqlSessionFactory.getConfiguration();

        // INFO: DCTANT: 2022/9/29 生成一个uuid，用于将这个SQL创建的MappedStatement注册到MybatisPlus中
        String sqlUuid = UUID.fastUUID().toString(true);
        RawSqlSource rawSqlSource = new RawSqlSource(configuration, sql, Object.class);
        MappedStatement.Builder builder = new MappedStatement.Builder(configuration, sqlUuid, rawSqlSource, SqlCommandType.SELECT);
        ArrayList<ResultMap> resultMaps = new ArrayList<>();
        // INFO: DCTANT: 2022/9/29 创建返回映射
        ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, UUID.fastUUID().toString(true), entityClass, new ArrayList<>());
        ResultMap resultMap = resultMapBuilder.build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);

        MappedStatement mappedStatement = builder.build();
        // INFO: DCTANT: 2022/9/29 将创建的MappedStatement注册到配置中
        configuration.addMappedStatement(mappedStatement);
        // INFO: DCTANT: 2022/9/29 使用SqlSession查询原生SQL
        List<SysUserMpgtPojo> list = sqlSession.selectList(sqlUuid);
        // INFO: DCTANT: 2022/9/29 关闭session
        sqlSession.close();
        return list;
    }

}
